package com.knowswift.issues.controller;

import com.knowswift.common.bean.issue.po.Issue;
import com.knowswift.common.bean.issue.po.MonitorDevice;
import com.knowswift.common.bean.issue.vo.IssueVO;
import com.knowswift.common.bean.project.po.Module;
import com.knowswift.common.bean.project.vo.ModulePermissionVO;
import com.knowswift.common.bean.project.vo.ModuleVO;
import com.knowswift.common.bean.project.vo.ProjectLimit;
import com.knowswift.common.common.Assert;
import com.knowswift.common.common.BaseResponse;
import com.knowswift.common.common.Page;
import com.knowswift.common.enums.IssueStatus;
import com.knowswift.common.utils.AliOSSUtil;
import com.knowswift.common.utils.OBSUtil;
import com.knowswift.common.utils.WrappedBeanCopier;
import com.knowswift.issues.util.DateUtil;
import com.knowswift.issues.util.FileUtils;
import com.knowswift.log.aop.AopLog;
import com.knowswift.security.account.User;
import com.knowswift.security.account.UserService;
import com.knowswift.security.util.AllowVisitor;
import com.obs.services.model.PutObjectRequest;
import com.obs.services.model.PutObjectResult;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@RestController
@RequestMapping("/app/issue/")
public class UserIssueController extends AbstractController {

    @PostMapping("/modules")
    @AopLog(name = "项目模块列表", platform = "用户端")
    public BaseResponse modules(@AuthenticationPrincipal User user, @RequestBody ModuleVO param) {
        Page<Module> page = new Page<>(param.getPageNo(), param.getPageSize());
        boolean allIssues = UserService.checkAuthority(user, "allIssues");
        boolean ownIssues = UserService.checkAuthority(user, "ownIssues");
        boolean projectIssues = UserService.checkAuthority(user, "projectIssues");
        if (!allIssues && !ownIssues && projectIssues) {
            Page<ModuleVO> page1 = new Page<>(param.getPageNo(), param.getPageSize());
            Page<ModulePermissionVO> voPage = modulePermissionService.getBaseMapper().getByUserIdPage(user.getUserId(), page1);
            modulePermissionService.concatData(voPage.getRecords());
            return BaseResponse.success(voPage);
        }
        page = moduleService.lambdaQuery().select(Module::getModuleName, Module::getProjects).orderByAsc(Module::getModuleOrder).page(page);
        return BaseResponse.success(page);
    }

    @PostMapping("/getOssToken")
    @AopLog(name = "获取上传token", platform = "用户端")
    public BaseResponse getOssToken(@RequestBody(required = false) IssueVO param) {
        Object token = param != null && "APP".equals(param.getType()) ? AliOSSUtil.getToken() : AliOSSUtil.getOSSToken();
        return BaseResponse.success(token);
//        System.out.println("===========================oss>"+token);
//        return BaseResponse.failure("哇哈哈");
    }

    @PostMapping("/report")
    @AopLog(name = "上报问题", platform = "用户端")
    public BaseResponse issue(@AuthenticationPrincipal User user, @Validated @RequestBody IssueVO param) {
        if (StringUtils.isBlank(param.getIssueId())) {
            System.out.println("=============参数"+param);
            Issue issue = WrappedBeanCopier.copyProperties(param, Issue.class);
            System.out.println("=============issue"+issue);
            issue.setCreateUserId(user.getUserId());
            issue.setPrimaryImage(param.getIssueImages().get(0));
            boolean save = issueService.save(issue);
            if (!save) {
                return BaseResponse.failure("上报失败");
            }
            asyncTask.saveMassage(issue);
            return BaseResponse.success();
        }
        Issue issue = issueService.getById(param.getIssueId());
        Assert.notNull(issue, "数据不存在");
        Assert.isTrue(!issue.getIssueStatus().equals(IssueStatus.PASS.getValue()), "上报已经审核通过，不可修改");
        WrappedBeanCopier.copyPropertiesIgnoreNull(param, issue);
        issue.setIssueStatus(IssueStatus.NEW.getValue());
        issue.setPrimaryImage(param.getIssueImages().get(0));
        boolean update = issueService.updateById(issue);
        return BaseResponse.condition(update, "修改失败");
    }

    @PostMapping("/issueModules")
    @AopLog(name = "项目模块列表", platform = "用户端")
    public BaseResponse issueModules(@AuthenticationPrincipal User user) {
        List<ModuleVO> list = issueService.getBaseMapper().getRecordModules(user.getUserId());
//        for (ModuleVO moduleVO : list) {
//            List<ProjectVO> projects = WrappedBeanCopier.JSONArrayToList(moduleVO.getProjects(), ProjectVO.class);
//            HashSet<ProjectVO> set = new HashSet<>(projects);
//            projects = new ArrayList<>(set);
//            moduleVO.setProjects(projects);
//        }
        return BaseResponse.success(list);
    }

    @PostMapping("/issues")
    @AopLog(saveLog = false, name = "上报记录", platform = "用户端")
    public BaseResponse issues(@AuthenticationPrincipal User user, @RequestBody IssueVO param) {

        Page<IssueVO> page = new Page<>(param.getPageNo(), param.getPageSize());
        page = issueService.getBaseMapper().getRecords(user.getUserId(), param.getModuleName(), param.getProjectName(),
                param.getIssueArea(), param.getIssueCode(), param.getIssueStatus(), page);
        return BaseResponse.success(page);
    }

    @PostMapping("/areaAndCodes")
    @AopLog(saveLog = false, name = "区域和编号列表", platform = "用户端")
    public BaseResponse areaAndCodes(@RequestBody IssueVO param) {
        List<Issue> list = issueService.lambdaQuery().eq(Issue::getModuleName, param.getModuleName())
                .eq(Issue::getProjectName, param.getProjectName()).select(Issue::getIssueArea, Issue::getIssueCode)
                .orderByDesc(Issue::getReportTime)
                .list();
        List<String> areas = new ArrayList<>();
        List<String> codes = new ArrayList<>();
        for (Issue issue : list) {
            if (!areas.contains(issue.getIssueArea())) {
                areas.add(issue.getIssueArea());
            }
            if (!codes.contains(issue.getIssueCode())) {
                codes.add(issue.getIssueCode());
            }
        }
        HashMap<String, List<String>> map = new HashMap<>();
        map.put("areas", areas);
        map.put("codes", codes);
        return BaseResponse.success(map);
    }

    @PostMapping("/deviceList")
    @AopLog(saveLog = false, name = "编号列表", platform = "用户端")
    public BaseResponse deviceList(@RequestBody IssueVO param) {
        List<MonitorDevice> list = monitorDeviceService.lambdaQuery()
                .eq(MonitorDevice::getModuleName, param.getModuleName())
                .eq(MonitorDevice::getProjectName, param.getProjectName())
                .select(MonitorDevice::getSerialNumber, MonitorDevice::getDeviceId, MonitorDevice::getModuleName,MonitorDevice::getProjectName)
                .list();
        return BaseResponse.success(list);
    }

    @PostMapping("/issueDetails")
    @AopLog(name = "上报详情", platform = "用户端")
    public BaseResponse issueDetails(@RequestBody IssueVO param) {
        Issue issue = issueService.getById(param.getIssueId());
        return BaseResponse.success(issue);
    }

    @PostMapping("/deleteIssue")
    @AopLog(name = "删除上报", platform = "用户端")
    public BaseResponse deleteIssue(@AuthenticationPrincipal User user, @RequestBody IssueVO param) {
        boolean remove = issueService.lambdaUpdate()
                .eq(Issue::getIssueId, param.getIssueId())
                .eq(Issue::getCreateUserId, user.getUserId())
                .remove();
        return BaseResponse.condition(remove, "删除失败");
    }

    @PostMapping("/issues2")
    @AopLog(saveLog = false, name = "上报列表", platform = "管理后台")
    public BaseResponse issues2(@AuthenticationPrincipal User user, @RequestBody IssueVO param) {
        Page<IssueVO> page = new Page<>(param.getPageNo(), param.getPageSize());
        // 判断用户是否有查看全部数据的权限
        boolean allIssues = UserService.checkAuthority(user, "allIssues");
        boolean ownIssues = UserService.checkAuthority(user, "ownIssues");
        boolean projectIssues = UserService.checkAuthority(user, "projectIssues");
        String userId = allIssues || projectIssues ? null : user.getUserId();
        List<String> strings = null;

        if (!allIssues && !ownIssues && projectIssues) {
            strings = new ArrayList<>();
            List<ModulePermissionVO> permissions = modulePermissionService.getBaseMapper().getByUserId(user.getUserId());
            for (ModulePermissionVO permission : permissions) {
                List<ProjectLimit> projectLimits = WrappedBeanCopier.JSONArrayToList(permission.getProjects(), ProjectLimit.class);
                for (ProjectLimit projectLimit : projectLimits) {
                    if (BooleanUtils.isTrue(projectLimit.getLimit())) {
                        strings.add(permission.getModuleName() + projectLimit.getProjectName());
                    }
                }

            }
        }
        page = issueService.getBaseMapper().getRecordsInAdmin(userId, param.getModuleName(), param.getProjectName(),
                param.getIssueArea(), param.getIssueCode(), IssueStatus.PASS.getValue(), strings, page);
        return BaseResponse.success(page);
    }

    @PostMapping("/relations")
    @AopLog(name = "关联的上报记录", platform = "管理后台")
    public BaseResponse relations(@RequestBody IssueVO param) {
        Issue issue = issueService.getById(param.getIssueId());
        Assert.notNull(issue, "数据不存在");
        Page<Issue> page = new Page<>(param.getPageNo(), param.getPageSize());
        page = issueService.lambdaQuery()
                .eq(Issue::getModuleName, issue.getModuleName())
                .eq(Issue::getProjectName, issue.getProjectName())
                .eq(Issue::getIssueArea, issue.getIssueArea())
                .eq(Issue::getIssueCode, issue.getIssueCode())
                .ne(Issue::getIssueId, issue.getIssueId())
                .eq(Issue::getIssueStatus, IssueStatus.PASS.getValue())
                .select(Issue::getIssueId, Issue::getReportTime, Issue::getIssueImages)
                .page(page);
        return BaseResponse.success(page);
    }





    @AllowVisitor(checkToken = false)
    @RequestMapping(value = "/batchUpload")
    @ResponseBody
    public BaseResponse batchUpload(HttpServletRequest request) throws Exception {
        List<String> back=uploadFile_ssi_uploader(request);
        return BaseResponse.success(back);
    }


    public List<String> uploadFile_ssi_uploader(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> files = Murequest.getFileMap();//得到文件map对象

        List<String> urlList = new ArrayList<>();

        for(MultipartFile file :files.values()){
            String  fileName=file.getOriginalFilename();//源文件名
            String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
            fileName= DateUtil.formateDate(new Date(),"yyyyMMddHHmmssSSS")+fileF;

			/*if(!FileUtils.checkFileSize(file.getSize(), 5120, "K")){
				throw new Exception("文件大小超过限制");
			}*/

            PutObjectRequest putObjectRequest = new PutObjectRequest();
            putObjectRequest.setBucketName("termitebk");
            String path="image/";
            path="";
            putObjectRequest.setObjectKey(path + fileName);
            putObjectRequest.setFile(FileUtils.convert(file));

            PutObjectResult res = OBSUtil.UploadOBS(putObjectRequest);

            urlList.add(res.getObjectUrl());

        }
        return urlList;
    }


}
